<?php

namespace addons\podunk\model;

use think\Model;
use app\common\library\Auth;
use think\Db;
use think\Log;
use fast\Random;
use addons\podunk\exception\Exception;

/**
 * 会员模型
 */
class User extends Model
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [
        'url',
    ];

    public static function info()
    {
        if(Auth::instance()->id) {
            return Auth::instance();
        }
        return null;
    }

    public static function getAgentList($search)
    {
        if($search){
            $where = [
                'username'=>['LIKE',"%".$search."%"],
                'nickname'=>['LIKE',"%".$search."%"],
                'mobile'=>['LIKE',"%".$search."%"]
            ];
        }else{
            $where = [];
        }

        $userList = self::where(['parent_id'=>Auth::instance()->id])->where(function($query) use($where){
            $query->whereOr($where);
        })->order('id desc')->paginate(10);

        if($userList){
            return $userList;
        }
        return null;
    }

    /**
     * 获取个人URL
     * @param   string $value
     * @param   array  $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }

    /**
     * 获取头像
     * @param   string $value
     * @param   array  $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            //$value = '/assets/img/avatar.png';
            $value = letter_avatar($data['nickname']);
        }

        return cdnurl($value, true);
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 注册用户
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param array  $extend   扩展参数
     * @return boolean
     */
    public static function register($username, $password, $email = '', $mobile = '', $extend = [])
    {
        // 检测用户名、昵称、邮箱、手机号是否存在
        if (self::getByUsername($username)) {
            throw new \Exception('用户名已存在');
        }
        if ($mobile && self::getByMobile($mobile)) {
            throw new \Exception('手机号已经存在');
        }

        $ip = request()->ip();
        $time = time();

        $data = [
            'username' => $username,
            'password' => $password,
            'email'    => $email,
            'mobile'   => $mobile,
            'level'    => 1,
            'score'    => 0,
            'avatar'   => '',
        ];
        $params = array_merge($data, [
            'nickname'  => preg_match("/^1[3-9]{1}\d{9}$/",$username) ? substr_replace($username,'****',3,4) : $username,
            'salt'      => Random::alnum(),
            'jointime'  => $time,
            'joinip'    => $ip,
            'logintime' => $time,
            'loginip'   => $ip,
            'prevtime'  => $time,
            'status'    => 'normal'
        ]);
        $params['password'] = md5(md5($password) . $params['salt']);
        $params = array_merge($params, $extend);

        //账号注册时需要开启事务,避免出现垃圾数据
        Db::startTrans();
        try {
            $user = User::create($params, true);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }
        return true;
    }

    /**
     * 变更会员端口
     * @param int    $port   端口数
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function port($port, $user_id, $memo)
    {
        $user = self::get($user_id);
        if ($user && $port != 0) {
            $before = $user->port;
            $after = $user->port + $port;
            //更新会员信息
            $user->save(['port' => $after]);
            //写入日志
            PortLog::create(['user_id' => $user_id, 'port' => $port, 'before' => $before, 'after' => $after, 'memo' => $memo]);
        }
    }

}
